package com.cx.common.secuity.aspect;

import com.cx.common.core.constant.SecurityConstants;
import com.cx.common.core.exception.InnerAuthException;
import com.cx.common.core.exception.auth.NotLoginException;
import com.cx.common.core.utils.JwtUtils;
import com.cx.common.core.utils.ServletUtils;
import com.cx.common.core.utils.StringUtils;
import com.cx.common.secuity.annotation.InnerAuth;
import com.cx.common.secuity.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 内部服务调用验证处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class InnerAuthAspect implements Ordered {
    @Around("@annotation(innerAuth)")
    public Object innerAround(ProceedingJoinPoint point, InnerAuth innerAuth) throws Throwable {
        String source = ServletUtils.getRequest().getHeader(SecurityConstants.FROM_SOURCE);
        // 内部请求验证
        if (!StringUtils.equals(SecurityConstants.INNER, source)) {
            throw new InnerAuthException("没有内部访问权限，不允许访问");
        }

        String token = SecurityUtils.getToken();
        if (StringUtils.isEmpty(token)) {
            throw new NotLoginException("用户未登录，请登录后重试");
        }
        //从token解析用户信息，设置到全局信息
        Claims claims = JwtUtils.parseToken(token);
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        String system = JwtUtils.getSystem(claims);
        // 用户信息验证
        if (innerAuth.isUser() && (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username) || StringUtils.isEmpty(system))) {
            throw new InnerAuthException("没有设置用户信息，不允许访问 ");
        }
        return point.proceed();
    }

    /**
     * 确保在权限认证aop执行前执行
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
